/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-29
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-01-30
 * @Description: 可复用的文本输入框组件，支持右侧自定义插槽和聚焦高亮
 */
import 'package:flutter/material.dart';

class CustomTextField extends StatefulWidget {
  final String label;
  final TextEditingController controller;
  final double labelFontSize;
  final String hintText;
  final Widget? rightSlot;
  final bool isPassword;
  final TextInputType keyboardType;
  final bool autoFocus;

  const CustomTextField({
    super.key,
    required this.label,
    required this.controller,
    this.labelFontSize = 16.0,
    required this.hintText,
    this.rightSlot,
    this.isPassword = false,
    this.keyboardType = TextInputType.text,
    this.autoFocus = false,
  });

  @override
  CustomTextFieldState createState() => CustomTextFieldState();
}

class CustomTextFieldState extends State<CustomTextField> {
  late bool isObscure; // 维护密码可见性状态
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    isObscure = widget.isPassword;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(bottom: 10.0),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: focusNode.hasFocus ? Colors.blue : Colors.grey,
            width: 1.0,
          ),
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 100.0,
            child: Text(
              widget.label,
              style: TextStyle(
                fontSize: widget.labelFontSize,
                color: Colors.black,
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextField(
              controller: widget.controller,
              focusNode: focusNode,
              obscureText: isObscure, // 这里正确控制密码可见性
              keyboardType: widget.keyboardType,
              autofocus: widget.autoFocus,
              decoration: InputDecoration(
                hintText: widget.hintText,
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                filled: false,
              ),
            ),
          ),
          if (widget.rightSlot != null) ...[
            const SizedBox(width: 8.0),
            widget.rightSlot!,
          ],
          if (widget.isPassword)
            IconButton(
              icon: Icon(
                isObscure ? Icons.visibility_off : Icons.visibility,
                color: Colors.grey,
              ),
              onPressed: () {
                setState(() {
                  isObscure = !isObscure;
                });
              },
            ),
        ],
      ),
    );
  }
}
